'use strict';

import React from 'react';
import { Link } from 'react-router';
import { connect } from 'react-redux';
import * as actions from '../../actions/ring_tags_step1';
import { Button,Search,Notice,Icon,
		 Dialog,Loading,Tab,Tag,Badge,
		 Form,Breadcrumb,Step,Field,DatePicker,
		 Input,Range,NumberPicker,Radio} from 'qnui';
import { Row, Col } from 'qnui/lib/grid';
import moment from 'qnui/lib/moment';
import './index.scss';

const FormItem = Form.Item;
const StepItem = Step.Item;
const RadioGroup = Radio.Group;

class RingTagsStep1 extends React.Component {
    constructor(props) {
        super(props);
		this.field = new Field(this, {
				scrollToFirstError:true,
				onChange: (name, value) => {
					if(name=="unit" && value=="h" && this.state.unit=="m"){
						this.field.setValue("countdown",this.field.getValue("countdown")/60);
					}
					if(name=="unit" && value=="m" && this.state.unit=="h"){
						const hours = this.field.getValue("countdown")*60
						this.field.setValue("countdown",hours>0?hours:0.5);
					}
					if(name=="unit"){
						switch(value){
							case "m":
								this.setState({
									"unit":"m",
									"rangeMax":60,
									"rangeMarks":6,
									"unitName":"分钟",
									"rangeStep":1,
								});
							break;
							case "h":
								this.setState({
									"unit":"h",
									"rangeMax":4,
									"rangeMarks":4,
									"unitName":"小时",
									"rangeStep":0.5,
								});
							break;
						}	
					}
					if(this.field.getState(name)=="success"){
						// this.props.dispatch(actions.setField(name,value));
					}
				}
			});
		this.dispatch = this.props.dispatch;
		this.state = {
			"unit":"m",
			"rangeMax":60,
			"rangeMarks":6,
			"unitName":"分钟",
			"rangeStep":1,
			overlayVisible:false,
            value: null,
			search:"",
			hasTag:false,
			isSelectTag:false,
			refreshDialog:false,
			refreshContent:"",
			editTag:false
		}
    }
	componentWillMount(){
		const editTag = (this.props.location.state);
		if(editTag){
			editTag.countdown = parseInt(editTag.countdown);
			const isMenut = editTag.countdown<=60;
			editTag.countdown = isMenut?editTag.countdown:editTag.countdown/60;
			this.field.setValue("unit",isMenut?"m":"h");
			this.field.setValues(editTag);
			this.setState({
				"tagStartDate":editTag.tag_start_time,
				"tagEndDate":editTag.tag_end_time,
				"editTag":true,
				"unit":isMenut?"m":"h",
				"rangeMax":isMenut?60:4,
				"rangeMarks":isMenut?6:4,
				"unitName":isMenut?"分钟":"小时",
				"rangeStep":isMenut?1:0.5,
			});
		}
	}
	disabledStartDate(calendarDate) {
		const early = Date.parse(this.state.tagStartDate);
		return calendarDate < (early-86400);
	}
	disabledEndDate(calendarDate) {
		const last = Date.parse(this.state.tagEndDate);
		return calendarDate > (last+86400);
	}
  	checkEndDate(rule,date,callback){
		if(!date){
			callback('必须有一个结束时间');
		}
		if (date && Date.parse(date) < Date.parse(this.field.getValue('startTime'))) {
            callback('结束时间必须晚于开始时间！');
        } 
		if (date && Date.parse(date) < Date.parse(new Date())) {
            callback('结束时间必须晚于当前系统时间！');
        } 
		if(this.editTag && date && Date.parse(date) < Date.parse(this.state.tagEndDate)){
			callback('结束时间不能晚于标签结束时间！');
		}
		{
            callback();
        }
	}
	contdownFormatter(value) {
        return  value+this.state.unitName;
    }
	rangeChange(val){
		switch(val){
			case "m":
				this.setState({
					"unit":"m",
					"rangeMax":60,
					"rangeMarks":6,
					"unitName":"分钟",
					"rangeStep":1,
				});
			break;
			case "h":
				this.setState({
					"unit":"h",
					"rangeMax":4,
					"rangeMarks":4,
					"unitName":"小时",
					"rangeStep":0.5,
				});
			break;
		}
	}
	onClose(){
		this.props.dispatch(actions.closeDialog());
	}
	onRefreshClose(){
		this.setState({"refreshDialog":false});
	}
	handleSubmit(e){
		e.preventDefault();
        this.field.validate((errors, values) => {
            if (errors) {
                return;
            }
				
			if(window.info.deadline_time < Date.parse(values.endTime)/1000){
				//截至时间不能晚于订购时间，请重新设置
				this.setState({"refreshDialog":true,"refreshContent":{"title":"订购时间不足，活动截止时间不能晚于订购时间","msg":"","content":<a target="_blank" href="https://fuwu.taobao.com/ser/detail.htm?service_code=FW_GOODS-1840332"><Button type="primary" size="large" shape="warning">续费</Button></a>}});
				return;
			}
			values.start_time = Date.parse(values.start_time)/1000;
			values.end_time = Date.parse(values.end_time)/1000;
			if(this.state.editTag){
				this.props.dispatch(actions.editTagTask(values));
			}else{
				this.props.dispatch(actions.createTag(values));
			}
        });
	}
	handleGo(type){
		const newTask = this.props.ring_tags_step1.newTask;
		switch(type){
			case "normal":
				this.props.history.pushState({...newTask}, '/ring_tags_step2?act_type=item');
				break;
			case "limit":
				this.props.history.pushState({...newTask}, '/ring_tags_step2?act_type=limit');
				break;
		}
		this.props.dispatch(actions.closeChoseDialog());
	}
	handleCloseChoseDialog(){
		this.props.dispatch(actions.closeChoseDialog());
	}
  render() {
	const init = this.field.init;
	const formItemLayout = {
		labelCol: {span: 6},
		wrapperCol: {span: 24},
	};	
	const loginBtn = this.props.ring_tags_step1.loginError?
						<a href="https://oauth.taobao.com/authorize?response_type=code&client_id=21127968&redirect_uri=http://llxl.hz.taeapp.com/?state=ring_tags_step1&view=web"><Button size="large" type="primary"><span>请重新登陆</span></Button></a>
					 :"";
    const footer = this.props.ring_tags_step1.loginError?<div>{loginBtn}</div>:"";
	const creatingTitle = this.props.ring_tags_step1.loading?"正在创建。。。":"错误信息";
	const creatingMsg = this.props.ring_tags_step1.loading?<Loading />:this.props.ring_tags_step1.message;
	const creatingDialog = this.props.ring_tags_step1.loading?true:this.props.ring_tags_step1.error;
	const cancleBtnText = this.state.editTag?"返回":"取消创建";
	const okBtnText = this.state.editTag?"修改":"创建活动";
    return <div className="ring-tags">
			<Dialog
				visible={this.props.ring_tags_step1.showChoseDialog}
				title="请选择创建折扣的类型："
				onClose={this.handleCloseChoseDialog.bind(this)}
				footer={false}
				>
				<Row>
						<Col span="12">
						<Button onClick={this.handleGo.bind(this,"normal")}>普通折扣</Button>
						</Col>
						<Col span="12" offset="2">
						<Button offset="2" onClick={this.handleGo.bind(this,"limit")}>限购折扣</Button>
						</Col>
				</Row>
			</Dialog>
			<Dialog
					visible = {this.state.refreshDialog}
                    onOk = {this.onRefreshClose.bind(this)}
                    onCancel = {this.onRefreshClose.bind(this)}
                    onClose = {this.onRefreshClose.bind(this)} 
					title = {this.state.refreshContent.title}
					style={{width:"445px",height:"360px"}}
					footer = {false}
					>
					<Row justify="center">
						{this.state.refreshContent.msg}
					</Row>
					<Row justify="center">
						{this.state.refreshContent.content}
					</Row>
            </Dialog>
			<Dialog style={{width:"600px",height:"360px"}} 
					visible = {creatingDialog}
                    onOk = {this.onClose.bind(this)}
                    onCancel = {this.onClose.bind(this)}
                    onClose = {this.onClose.bind(this)} 
					title = {creatingTitle}
					footer = {footer}
					>
					<Row justify="center">
						<h3>{creatingMsg}</h3>
					</Row>
            </Dialog>
          <Row style={{background:"#F6F6F6",margin:"3px 0"}} justify="start">
			<Col span="8" align="center">
			<Breadcrumb maxNode={5}>
				  <Breadcrumb.Item>连环折扣</Breadcrumb.Item>
				  <Breadcrumb.Item>创建</Breadcrumb.Item>
				  <Breadcrumb.Item>设置标签</Breadcrumb.Item>
			  </Breadcrumb>
			</Col>
			<Col offset="2">
					<Step current={0} type="dot">
						<StepItem title="设置标签" />
						<StepItem title="创建折扣"/>
						<StepItem title="选择商品"/>
						<StepItem title="完成"/>
					</Step>
			</Col>
		  </Row>
		  <Row justify="start" style={{marginTop:"50px"}}>
		   <Form direction="ver"  size="large" field={this.field}>
            <Col>
			  <FormItem
					label="标签"
					required 
					{...formItemLayout}>
					<Input placeholder="标签名称，该名字不会被公布。" 
						   {...init('tag_name', {
								rules: [
                                {required: true,whitespace:true, message: '请输入一个标签名，该名字不会被公布。'},
								],
							})}  
							disabled={this.state.editTag}
							/>
			  </FormItem>
			  <FormItem
					label="活动备注"
					required 
					{...formItemLayout}>
					<Input placeholder="请输入描述" 
							{...init('tag_desc', {
								rules: [
                                {required: true,whitespace:true, message: '对这个标签进行描述'},
								],
							})}  
							disabled={this.state.editTag}
							/>
			  </FormItem>
			  <FormItem
					label="时间设置"
					{...formItemLayout}>
					<Row>
                        <FormItem required label="开始"><DatePicker disabledDate={this.disabledStartDate.bind(this)} size="large" {...init('start_time',{rules: [{required: true,message:"请设置开始时间"}]})} showTime/></FormItem>
						<FormItem required label="结束"><DatePicker disabledDate={this.disabledEndDate.bind(this)} size="large" {...init('end_time',{rules: [{validator:this.checkEndDate.bind(this)}]})} showTime/></FormItem>
                    </Row>
			  </FormItem>
			  <FormItem
					label="倒计时"
					required 
					{...formItemLayout}>
					<Col span="3">
						<RadioGroup 
							{...init('unit')}
							defaultValue="m" 
						>
							<Radio id="minutes" value="m">分钟</Radio>
							{/*<Radio id="hours" value="h">小时</Radio>*/}
						</RadioGroup>
					</Col>
					<Col span="5">
						<NumberPicker 
							{...init('countdown',{rules: [{required: true,message:"倒计时不能少于1分钟"}]})}
							type="inline" 
							step={this.state.rangeStep} 
							min={0}
							max={this.state.rangeMax} 
							defaultValue={10} 
						/>
					</Col>
					<Col style={{paddingTop:"25px",marginBottom:"-25px"}} span="14">
						<Range 
							{...init('countdown',{rules: [{required: true,message:"倒计时不能少于1分钟"}]})}
							defaultValue={10} 
							step={this.state.rangeStep} 
							tipFormatter={this.contdownFormatter.bind(this)}  
							min={0} 
							max={this.state.rangeMax} 
							marks={this.state.rangeMarks} 
						/>
					</Col>
			  </FormItem>
			  <FormItem
					label=""
					{...formItemLayout}>
						<Link to="ring_tags">
							<Button size="large" type="normal">
								<span>{cancleBtnText}</span>
							</Button>
						</Link>
						<Button htmlType="submit" onClick={this.handleSubmit.bind(this)} style={{marginLeft:"20px"}} size="large" type="primary">
							{okBtnText}
						</Button>
			  </FormItem>
			</Col>
		   </Form>
		  </Row>
    </div>;
  }
}

export default connect((state)=> {
  return {
    ring_tags_step1: state.ring_tags_step1
  };
})(RingTagsStep1);
